import { isFuncThenExe } from './index'

/** 计时模式 */
export enum CounterModeEnum {
  /** 计时器 */
  TIMER = 'timer',
  /** 倒计时 */
  COUNTDOWN = 'countdown'
}

/**
 * 计时器回调及其相关配置
 */
interface ICounterOptions {
  /**
   * 开始前的回调
   */
  // startCall?: Function,

  /**
   * 结束的回调
   */
  stopCall?: Function
  /**
   * 运行时态的回调, 接收一个参数为当前秒数seconds
   */
  runingCall?: Function
}

class Counter {
  private _mode = CounterModeEnum.TIMER
  /** 计时器 */
  private _timer: NodeJS.Timer = null as unknown as NodeJS.Timer

  /** 运行标志 */
  private _isRuning = false
  public get isRuning(): boolean {
    return this._isRuning
  }

  /** 初始化时设置的秒数，用于开始时重置及结束判断标志 */
  private _initSeconds = undefined

  /** 秒数 */
  private _seconds = 0
  public get seconds(): number {
    return this._seconds
  }

  private _options: ICounterOptions = {} as ICounterOptions
  /**
   * mode 模式， 可设置为计时器 或 倒计时
   * seconds 设置秒数，计时器模式中传入则为结束秒数，倒计时模式则为倒计时秒数
   */
  constructor(mode?: CounterModeEnum, seconds?: number, options?: ICounterOptions) {
    // 设置模式
    if (mode) this._mode = mode as CounterModeEnum

    // 计时器模式
    if (mode === CounterModeEnum.TIMER && seconds) {
      this._initSeconds = seconds
    } else if (mode === CounterModeEnum.COUNTDOWN && seconds) {
      // 倒计时模式
      this._seconds = seconds
      this._initSeconds = seconds
    }

    if (options) this._options = options
  }

  start() {
    console.log('this', this)
    // if(this._timer) clearInterval(this._timer)
    if (this._isRuning) return

    // 重置秒数
    this.resetSeconds()
    this._isRuning = true

    // // 开始的回调
    // isFuncThenExe(this._options.startCall)

    this._timer = setInterval(() => {
      console.log('in time', this._mode, this._seconds)

      // 计时器处理
      if (this._mode === CounterModeEnum.TIMER) {
        this._seconds++
        // 运行时的回调(注：需在计算后回调，否则外部获取到值始终多1s)
        isFuncThenExe(this._options.runingCall, this._seconds)
        if (this._initSeconds !== undefined && this.seconds >= this._initSeconds)
          this.stop(this._options.stopCall)
      } else if (this._mode === CounterModeEnum.COUNTDOWN) {
        // 倒计时处理
        this._seconds--
        // 运行时的回调(注：需在计算后回调，否则外部获取到值始终多1s)
        isFuncThenExe(this._options.runingCall, this._seconds)
        if (this._seconds <= 0) this.stop(this._options.stopCall)
      }
    }, 1000)
  }

  /**
   * 结束计时
   */
  stop(fn?: Function) {
    this._isRuning = false
    clearInterval(this._timer)
    this._timer = null as unknown as NodeJS.Timer

    // 重置秒数
    // this.resetSeconds()

    // 结束的回调
    isFuncThenExe(fn)
  }

  /** 重置秒数 */
  resetSeconds() {
    if (this._mode === CounterModeEnum.TIMER) this._seconds = 0
    else if (this._mode === CounterModeEnum.COUNTDOWN) this._seconds = this._initSeconds
  }
}

export default Counter
